const app = getApp();
const getPosition = {
	getPosition: function(fn, type) {
		var data;
		try {
			var value = uni.getStorageSync('currlocation');
			if (value && !type) {
				data = {
					latitude: value.split(',')[1],
					longitude: value.split(',')[0]
				};
				fn(data);
			} else {
				posi(function(data) {
					fn(data);
				});
			}
		} catch (e) {
			console.log('CatchClause', e);
			console.log('CatchClause', e);
			// Do something when catch error
			posi(function(data) {
				fn(data);
			});
		}

		function posi(fn) {
			// 平台切换
			app.globalData.locationFn({
				type: 'gcj02',
				success(res) {
					// 定位成功
					var lnglat = res.longitude + ',' + res.latitude;
					uni.setStorage({
						key: 'currlocation',
						data: lnglat
					});
				},
				fail(res) {
					// 定位失败
					if (app.globalData.siteDebug) {
						uni.showModal({
							title: '定位失败',
							content: JSON.stringify(res),
							success(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
					//仅针对后台定位类型和线上不符的情况，其他情况暂不做处理
					let failStr = `fail the api need to be declared in the requiredPrivateInfos`;
					if (res.errMsg.includes(`getLocation:${failStr}`)) { //精确定位失效
						app.globalData.appConfig.cfg_miniProgramLocationAuth = 'chooseLocation';
						posi(fn)
					} else if (res.errMsg.includes(`getFuzzyLocation:${failStr}`)) { //模糊定位失效
						app.globalData.appConfig.cfg_miniProgramLocationAuth = 'getLocation';
						posi(fn)
					}
					// if (res.errMsg.includes(
					// 		'fail the api need to be declared in the requiredPrivateInfos')) {
					// 	uni.showModal({
					// 		title: '定位失败！',
					// 		content: '小程序定位类型出错，请联系管理员',
					// 	})
					// }
				},
				complete(res) {
					fn(res);
				}
			});
		}
	}
}
export default getPosition;